import validate from 'wechat-validate'

Page({
  // 通过behaviors注入validate方法
  behaviors: [validate],
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' }
    ],
    code: [
      { required: true, message: '请填写验证码' },
      { pattern: /^\d{6}$/, message: '请填写正确的验证码!' }
    ]
  },
  data: {
    countDownVisible: false,
    mobile: '',
    code: ''
  },
  onLoad (query) {
    // 获取重定向地址
    this.query = query
    console.log(query)
  },
  //倒计时变化
  countDownChange (ev) {
    this.setData({
      // 倒计时组件数据
      timeData: ev.detail,
      //是否显示倒计时组件
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0
    })
  },
  // 获取验证码
  async getSMSCode () {
    const { valid, message } = this.validate('mobile')
    if (valid) {
      const { data: res } = await wx.http.get('/code', { mobile: this.data.mobile })
      console.log(res)
      this.setData({
        countDownVisible: true
      })
    } else {
      wx.utils.toast(message)
    }
  },
  // 登录表单提交
  async onSubmit () {
    const { mobile, code } = this.data
    // 校验，不传参是校验全部
    // 验证数据是否合法
    const isValidate = this.validate()
    if (isValidate) {
      const { data } = await wx.http.post('/login', { mobile, code })
      const app = getApp()
      app.setToken('token', data.token)
      app.setToken('refreshToken', data.refreshToken)
      wx.redirectTo({
        url: this.query.route
      })
    }
  }
})
